package com.base.essearch.config;

import com.base.essearch.video.task.MediaProcessTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.regex.Pattern;

/**
 * @Description TODO
 * @Author haijun
 * @Date 2019/12/30 13:57
 * @ClassName FileMvcConfig
 ***/
@Configuration
public class FileMvcConfig implements WebMvcConfigurer {

    /**
     * 网络路径配置
     */
    @Value("${upload.config.staticAccessPath}")
    private String staticAccessPath;

    /**
     * 服务器储存路径（带盘符，liunx不用）
     */

    private String uploadFolder;

    @Value("${upload.config.windows}")
    private String windows;
    @Value("${upload.config.linux}")
    private String linux;

    /**
     * 服务器储存子路径
     */
    @Value("${upload.config.localPath}")
    private String localPath;
    /**
     * 用户头像
     **/
    @Value("${upload.config.userHeaderPicPath}")
    private String userHeaderPic;
    /**
     * 档案文件数据
     */
    @Value("${upload.config.archivesFilePath}")
    private String archivesFilePath;
    //
//    @Autowired
//    private IConfigService configService;
    public static String filePath;
    public static String priFilePath;
    public static String staticUploadFolder;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置server虚拟路径，handler为前台访问的目录，locations为files相对应的本地路径
        registry.addResourceHandler(staticAccessPath)
                .addResourceLocations("file:" + getUploadFolder() + localPath);
        filePath = getUploadFolder() + localPath;
        priFilePath = staticAccessPath;
        staticUploadFolder = getUploadFolder();
        MediaProcessTask.serverPath = getUploadFolder() + localPath;
    }

    public String getUploadFolder() {
        System.out.println("uploadFolder: " + uploadFolder);
        return uploadFolder;
    }

    public static String getFilePath(String neturl) {
        // neturl="storage/m3u8/1337013991604178945/e626d75649779d9778e2c5cf2c4c337d/hls/e626d75649779d9778e2c5cf2c4c337d.m3u8";
        return neturl.replaceFirst(priFilePath.replace("*", ""), filePath);
    }

    @PostConstruct
    public void init() {
        if (isWindowsSystem()) {
            uploadFolder = windows;
        } else {
            uploadFolder = linux;
        }
        File file = new File(uploadFolder);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 判断系统是win linux
     *
     * @return
     */
    public static boolean isWindowsSystem() {
        String osName = System.getProperty("os.name");
        if (Pattern.matches("Windows.*", osName)) {
            return true;
        }
        return false;
    }
}
